package com.example.a2209_shop.login

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.a2209_shop.utils.SingleLiveData
import com.example.base.entity.UserEntityResult
import com.example.base.mvvm.BaseViewModel
import com.example.base.net.ApiServer
import com.example.base.net.Const
import com.example.base.net.RetrofitUtil
import com.google.gson.Gson
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody

class LoginViewModel:BaseViewModel() {
    val loginSuccess = MutableLiveData<UserEntityResult>()
    val loginFail = SingleLiveData<String>()

    fun login(username:String,password:String){
        viewModelScope.launch {
            try {
                val map = mutableMapOf<String,String>()
                map[Const.PARAM_USERNAME] = username
                map[Const.PARAM_PASSWORD]  = password
                val json = Gson().toJson(map)
                val body = RequestBody.create("application/json;charset=utf-8".toMediaType(),json)
                loginSuccess.value = apiServer.login(body)
            }catch (e:Exception){
                //请求失败的情况
                e.message?.let { loginFail.postValue(it) }
            }
        }
    }
}